package com.REPDPMSystem.Service.Handler;
import com.REPDPMSystem.Service.FileService;
import com.REPDPMSystem.Utils.FileTypeUtil;
import com.REPDPMSystem.Entity.MyFile;
import com.REPDPMSystem.Mapper.FileMapper;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.List;
import java.util.UUID;

//
@Service
public class FileHandler extends ServiceImpl<FileMapper, MyFile> implements FileService {
    //TODO:文件类型检验 将handler写完整
    @Override
    public boolean upLoad(MyFile myfile, MultipartFile multipartFile) throws IOException {

        if (multipartFile != null) {
            myfile.setFile_id(UUID.randomUUID().toString());
            myfile.setFile_type(FileTypeUtil.getType(multipartFile).name());

            String filePath = "C://Users//deathwing475//Desktop//REPDPMSystem//assets//" + myfile.getFile_name();
            myfile.setFile_path(filePath);

            File saveFile = new File(filePath);
            multipartFile.transferTo(saveFile);        // 文件保存

            createNewFileInFolder(myfile);
            return true;
        }
        return false;

    }
    @Override
    public void downLoad(HttpServletResponse response, String filePath){
        File file = new File(filePath);
        if(!file.exists()){
            System.out.println("error");
            return;
            //return "下载文件不存在";
        }
        try (FileInputStream fis = new FileInputStream(filePath);
             BufferedInputStream bis = new BufferedInputStream(fis);
             OutputStream os = response.getOutputStream()) {    //  OutputStream 是文件写出流，讲文件下载到浏览器客户端
            // 新建字节数组，长度是文件的大小，比如文件 6kb, bis.available() = 1024 * 6
            byte[] bytes = new byte[bis.available()];
            // 从文件流读取字节到字节数组中
            bis.read(bytes);
            response.reset();
            response.setContentType("application/octet-stream");
            response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(filePath, "UTF-8"));
            // 重置 response
            //response.reset();
            // 设置 response 的下载响应头
            //response.setContentType("application/octet-stream");
            //response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));  // 注意，这里要设置文件名的编码，否则中文的文件名下载后不显示
            // 写出字节数组到输出流
            os.write(bytes);
            // 刷新输出流
            os.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }



//使用 BufferedInputStream 包装 FileInputStream，并在 try-with-resources 语句中自动关闭输入流。
//        try(BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file))) {
//            byte[] buff = new byte[1024];
//            OutputStream os  = response.getOutputStream();//获取响应的输出流。
//            int i = 0;
//            while ((i = bis.read(buff)) != -1) {//循环读取文件内容，将读取的字节数据存入缓冲区 buff，并将读取的字节数赋值给变量 i。
//                os.write(buff, 0, i);//将读取到的字节数组写入响应的输出流。
//                os.flush();//将缓冲区中的数据刷新到客户端。
//            }
//        } catch (IOException e) {
//            return "下载失败";
//        }
//        return "下载成功";
    }
    @Override
    public List<MyFile> getFileByFolderId(String folderId){
        QueryWrapper<MyFile> wrapper = new QueryWrapper<>();
        wrapper.eq("folder_id",folderId);
        return baseMapper.selectList(wrapper);
    }
    @Override
    public List<MyFile> getFileInfoByName(String name,String folder_id){
        QueryWrapper<MyFile> wrapper = new QueryWrapper<>();
        wrapper.like("file_name",name)
                .eq("folder_id",folder_id);
        return baseMapper.selectList(wrapper);

    }
    @Override
    public int createNewFileInFolder(MyFile file){
        file.setFile_id(UUID.randomUUID().toString());
        return baseMapper.insert(file);
    }
    @Override
    public boolean deleteFileByFileId(String fileId){
        QueryWrapper<MyFile> wrapper = new QueryWrapper<>();
        wrapper.eq("file_id", fileId);
        return baseMapper.delete(wrapper)>0;
    }
    @Override
    public boolean deleteFileByFolderId(String folderId){
        QueryWrapper<MyFile> wrapper = new QueryWrapper<>();
        wrapper.eq("folder_id",folderId);
        if(baseMapper.selectList(wrapper).isEmpty())return true;
        return baseMapper.delete(wrapper)>0;
    }

    @Override
    public long countUploadedFilesByEmployeeAndTimePeriod(String employeeId, long startTime, long endTime) {
        QueryWrapper<MyFile> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("staff_id", employeeId); // 查询条件：员工ID
        queryWrapper.between("date", startTime, endTime); // 查询条件：时间段

        return baseMapper.selectCount(queryWrapper); // 统计符合条件的记录数量
    }

    @Override
    public List<MyFile> getUploadedFilesByEmployeeAndTimePeriod(String employeeId, long startTime, long endTime) {
        QueryWrapper<MyFile> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("staff_id", employeeId); // 查询条件：员工ID
        queryWrapper.between("date", startTime, endTime); // 查询条件：时间段

        return baseMapper.selectList(queryWrapper);
    }
}

